package com.ddxz.shiro.test;

import com.ddxz.tool.core.common.DdxzJwtUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.*;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/11/25
 */

public class CustomRealm extends AuthorizingRealm {
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof DdxzToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if(principals == null || principals.isEmpty()) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }

        String username = (String)jwtUtil.getBody((String)principals.getPrimaryPrincipal()).get("username");
        List<String> roles = roleList.get(username);
        Set<Permission> permissions = new HashSet<>();
        roles.forEach(role -> permissionList.get(role).forEach(per -> permissions.add(new DdxzPermission(per))));
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setObjectPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), NAME);
    }

    private static final String NAME = "CUSTOM_REALM";

    private static final DdxzJwtUtil jwtUtil = new DdxzJwtUtil();

    private static final Map<String, String> userList = new HashMap<>(5);

    private static final Map<String, List<String>> roleList = new HashMap<>(5);

    private static final Map<String, List<String>> permissionList = new HashMap<>(2);

    static {
        userList.put("admin", "admin@123");
        userList.put("user1", "user1@123");
        userList.put("user2", "user2@123");
        userList.put("user3", "user3@123");
        userList.put("user4", "user4@123");

        roleList.put("admin", Arrays.asList("admin"));
        roleList.put("user1", Arrays.asList("normal", "admin"));
        roleList.put("user2", Arrays.asList("normal"));
        roleList.put("user3", Arrays.asList("normal"));
        roleList.put("user4", Arrays.asList("normal"));

        permissionList.put("admin", Arrays.asList("/path/dir", "/user/**", "/dept/**", "/role/**"));
        permissionList.put("normal", Arrays.asList("/path/dir", "/user/**", "/dept/info", "/dept/list"));
    }
}
